package com.shopping.handler;

import com.alibaba.fastjson2.JSONObject;
import com.shopping.commons.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登陆失败处理器，该处理器实现AuthenticationFailureHandler
 * 当用户登陆成功后会自动执行该处理器里的onAuthenticationFailure方法
 */
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        String errMsg = "";
        if (exception.getClass() == UsernameNotFoundException.class) {
            errMsg = "用户名不存在";
        } else if (exception.getClass() == BadCredentialsException.class) {
            errMsg = "密码错误";
        } else if (exception.getClass() == LockedException.class) {
            errMsg = "账户被冻结";
        }
        System.out.println("ssssssssssssssssss");
        System.out.println(errMsg);
        //401:认证未通过
        response.getWriter().println(JSONObject.toJSONString(Result.fail(401, errMsg)));
    }
}
